package com.ycode.bang.anbang.network;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.JsonSyntaxException;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.network.servicelistener.WithJsonListener;
import com.ycode.bang.anbang.utils.RequestMapDev;
import com.ycode.bang.anbang.utils.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

/**
 *
 */
public class FinalHttpService {
    private static final String TAG = "FinalHttpService";
    private static Context mContext;
    public static final String ERROR_NETWORK_UNAVAILABLE = "-1";
    public static final String ERROR_DATA_EXCEPTION = "-2";
    public static final String ERROR_UNKNOWN = "-99";
    public final static String JSONERROR_RESPONSECODE = "{\"code\":2,\"msg\":\"返回出错！\"}";

    private static final String PREFS_NAME = "tokenPreference";
    private static String mToken;
    private static String mLoginName;
    private static String mPassword;
    private static int mUser_id;
    private static String mUser_type;     //用户角色 （CLIENT：买家，SUPPLIER：卖家）
    private static String mUser_plat;     //登陆方式 NORMAL（普通） “”（第三方）
    private static String mUser_cookie;     //在线标志

    private static final String PREF_KEY = "token";
    private static final String PREF_ID = "id";
    private static final String PREF_LOGINNAME_KEY = "loginname";
    private static final String PREF_PASSWORD_KEY = "password";
    private static final String PREF_USERTYPE_KEY = "user_type";
    private static final String PREF_USERPLAT_KEY = "user_plat";
    private static final String PREF_USERCOOKIE_KEY = "user_cookie";
    private static final String PREF_USERPAY_KEY = "user_payresult";
    private static final String PREF_USERWXLOGIN_KEY = "weixin_login";

    public static final String PREF_ISFIRSTOPEN_KEY = "is_firstopen";
    public static final String hadMainActivity = "hadMainActivity";
    public static final String hadHandlePhoto = "hadHandlePhoto";
    public static final String hadSelectProduct = "hadSelectProduct";
    public static final String hadDetailProduct = "hadDetailProduct";
    public static final String hadSelectSupply = "hadSelectSupply";
    public static final String hadOrderReview = "hadOrderReview";

    public static final String jpushType = "jpush_type";
    public static final String action_jpush_check = "com.mypush";

    public static final String WXAppId = "wx8c0fde2cc9dcabe0";


    public static void init(Context context) {
        mContext = context;
        SharedPreferences tokenPreference = context.getSharedPreferences(PREFS_NAME, 0);
        mToken = tokenPreference.getString(PREF_KEY, "");
        mLoginName = tokenPreference.getString(PREF_LOGINNAME_KEY, "");
        mPassword = tokenPreference.getString(PREF_PASSWORD_KEY, "");
        mUser_type = tokenPreference.getString(PREF_USERTYPE_KEY, "");
    }


    /**
     * 上传图片
     *
     * @param imagepath
     * @paramlistener
     */
    public static void upLoadImage(String imagepath, final WithJsonListener listener) {

//        if (!BiaoShiApplication.instance.isNetworkConnected()) {
//            listener.onError(ERROR_NETWORK_UNAVAILABLE, mContext.getString(R.string.network_unavailable));
//            return;
//        }
        FinalHttpUtil mFinalHttp = new FinalHttpUtil();
        AjaxParams mAjaxParams = new AjaxParams();
//        mAjaxParams.put("csrfToken", MyApp.instance.getToken());
        try {
            mAjaxParams.put("file", new File(imagepath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mFinalHttp.post(RequestMapDev.UPLOUD + "?csrfToken=" + MyApp.instance.getToken(), mAjaxParams, new AjaxCallBack<Object>() {
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                ToastUtil.logE("uploadimage--onFailure-", strMsg);
                listener.onError(String.valueOf(errorNo), strMsg);
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                ToastUtil.logE("uploadimage--onSuccess-", o.toString());
                try {
                    JSONObject response = new JSONObject(o.toString());
                    String status = response.getString("status");
                    String message = response.getString("message");
                    String data = response.getString("data");
                    if (status.equals("0")) {
                        listener.onSuccess(status, message, data);
                    } else if (status.equals("BS001")) {
                        listener.onCookieError("BS001", "Cookie失效，请重新登录！");
                    } else {
                        listener.onError(status, message);
                    }
                } catch (JSONException e) {
                    listener.onError(ERROR_DATA_EXCEPTION, "数据异常");
                } catch (JsonSyntaxException e) {
                    listener.onError(ERROR_DATA_EXCEPTION, "数据异常");
                }

            }
        });

    }
}
